package com.seari.custody.controller;

import cn.hutool.core.date.CalendarUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.seari.custody.bean.AgendaFile;
import com.seari.custody.bean.PersonalAgenda;
import com.seari.custody.component.MinIoUtil;
import com.seari.custody.constant.MessageConstant;
import com.seari.custody.pojo.MessageBean;
import com.seari.custody.service.PersonalAgendaService;
import com.seari.custody.util.GenerateDateTimeUniqueID;
import com.seari.custody.util.HandlerNullUtils;
import com.seari.custody.util.JwtTokenUtils;
import com.seari.custody.util.UUIDUtils;
import io.minio.ObjectStat;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

@RestController
public class PersonalAgendaController {

    @Value("${minio.personagenda.bucket}")
    private String personAgenda;//minio project pdf桶地址

    @Autowired
    private PersonalAgendaService personalAgendaService;

    @Autowired
    private MinIoUtil minIoUtil;

    /**
     * 查询个人日程列表
     */
    @RequestMapping(value = "/agenda/slectMeeting")
    public MessageBean getMeetingArrangByMpid(HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        String userId = JwtTokenUtils.getUserId(tokenHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            String year = "";
            String weeked = "";
            //当前年份
            year = request.getParameter("year");
            //当前周数
            weeked = request.getParameter("week");
            if (HandlerNullUtils.objectIsNull(year)) {
                year = String.valueOf(DateUtil.thisYear());
            }
            if (HandlerNullUtils.objectIsNull(weeked)) {
                weeked = String.valueOf(DateUtil.thisWeekOfYear());
            }

            Calendar calendar = CalendarUtil.calendar();
            calendar.set(Calendar.YEAR, Integer.parseInt(year));
            calendar.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(weeked));

            Date startTime = CalendarUtil.beginOfWeek(calendar).getTime();
            Date endTime = DateUtil.offset(CalendarUtil.endOfWeek(calendar).getTime(), DateField.DAY_OF_WEEK, -2);

            List<PersonalAgenda> personalAgendaList = personalAgendaService.getAgendaByMpid(userId, DateUtil.format(startTime, DatePattern.NORM_DATETIME_PATTERN), DateUtil.format(endTime, DatePattern.NORM_DATETIME_PATTERN));

            //当前年份
            dataMap.put("year", year);
            //上一周年数
            dataMap.put("theyear", String.valueOf(DateUtil.year(DateUtil.offsetWeek(calendar.getTime(), -1))));
            //下一周年数
            dataMap.put("afteryear", String.valueOf(DateUtil.year(DateUtil.offsetWeek(calendar.getTime(), 1))));
            //上一周的周数
            dataMap.put("start", String.valueOf(DateUtil.weekOfYear(DateUtil.offsetWeek(calendar.getTime(), -1))));//开始日期
            //下一周的周数
            dataMap.put("ending", String.valueOf(DateUtil.weekOfYear(DateUtil.offsetWeek(calendar.getTime(), 1))));//开始日期
            //当前第几周
            dataMap.put("MonthWeek", weeked);
            //当前周周一时间
            dataMap.put("startdate", DateUtil.format(startTime, DatePattern.NORM_DATE_PATTERN));
            //当前周周五时间
            dataMap.put("dateclosed", DateUtil.format(endTime, DatePattern.NORM_DATE_PATTERN));

            dataMap.put("data", personalAgendaList);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("查询个人日程列表成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("查询个人日程列表失败");
        }
        return messageBean;
    }

    /**
     * 删除个人个人日程信息
     *
     * @return
     */
    @RequestMapping(value = "/agenda/deleteAgendaInfoByUuid")
    public MessageBean deleteAgendaInfoByUuid(@RequestBody Map<String, Object> map) {
        MessageBean messageBean = new MessageBean();
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            String uuid = (String) map.get("uuid");

            personalAgendaService.deleteAgendaInfoByUuid(uuid);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("删除个人日程信息成功 ");
            messageBean.setData(1);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setData(0);
            messageBean.setMessage("删除个人日程信息失败");
        }
        return messageBean;
    }

    /**
     * 获取个人日程的UUID
     *
     * @return
     */
    @RequestMapping(value = "/agenda/getAgendaInfoUuid")
    public MessageBean getAgendaInfoUuid() {
        MessageBean messageBean = new MessageBean();
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            String uuid = UUIDUtils.getUUID();
            dataMap.put("uuid", uuid);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("获取个人日程的UUID成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("获取个人日程的UUID失败");
        }
        return messageBean;
    }

    /**
     * 添加/修改个人日程信息
     *
     * @param personalAgenda
     * @return
     */
    @RequestMapping(value = "/agenda/addAgendaInfo")
    public MessageBean addAgendaInfo(@RequestBody PersonalAgenda personalAgenda, HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        try {
            String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
            String userId = JwtTokenUtils.getUserId(tokenHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
            personalAgenda.setUserId(userId);

            Map<String, Object> dataMap = new HashMap<String, Object>();
            personalAgendaService.addAgendaInfo(personalAgenda);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("添加/修改个人日程信息成功");
            messageBean.setData(1);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setData(0);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("添加/修改个人日程信息失败");
        }
        return messageBean;
    }

    /**
     * 通过UUid查询个人日程详细信息
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/agenda/selectAgendaInfoByUuid")
    public MessageBean selectAgendaInfoByUuid(@RequestBody Map<String, Object> map) {
        MessageBean messageBean = new MessageBean();
        try {
            String uuid = (String) map.get("uuid");
            Map<String, Object> dataMap = new HashMap<String, Object>();
            //查询个人日程信息
            PersonalAgenda personalAgenda = personalAgendaService.selectAgendaInfoByUuid(uuid);
            //查询个人日程附件信息
            List<AgendaFile> agendaFileList = personalAgendaService.selectAgendaAttachFileList(uuid);
            personalAgenda.setAgendaFileList(agendaFileList);
            dataMap.put("personalAgenda", personalAgenda);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("查询个人日程详细信息成功");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("查询个人日程详细信息失败");
        }
        return messageBean;
    }


    /**
     * 查询个人日程详细信息列表
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/agenda/selectAgendaInfoList")
    public MessageBean selectAgendaInfoList(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        try {
            String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
            String userId = JwtTokenUtils.getUserId(tokenHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int year = cal.get(Calendar.YEAR);
            int week = cal.get(Calendar.WEEK_OF_YEAR);

            Map<String, Object> dataMap = new HashMap<String, Object>();

            List<PersonalAgenda> personalAgendaList = null;
            if (HandlerNullUtils.objectIsNull(map.get("year")) || HandlerNullUtils.objectIsNull(map.get("week"))) {
                personalAgendaList = personalAgendaService.selectAgendaInfoListByYearAndWeek(year, week, userId);
            } else {
                year = (Integer) map.get("year");
                week = (Integer) map.get("week");
                personalAgendaList = personalAgendaService.selectAgendaInfoListByYearAndWeek(year, week, userId);
            }

            dataMap.put("personalAgendaList", personalAgendaList);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("查询个人日程详细信息列表成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("查询个人日程详细信息列表失败");
        }
        return messageBean;
    }

    /**
     * 上传个人日程附件
     * 含有（多文件上传）
     *
     * @return
     */
    @RequestMapping(value = "/agenda/uploadAgendaAttachFile")
    public MessageBean uploadAgendaAttachFile(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {

        MessageBean messageBean = new MessageBean();
        MultipartFile file;
        String agendaUuid;
        String fileSize;
        try {
            agendaUuid = request.getParameter("uuid");
            fileSize = request.getParameter("fileSize");
            //返回文件列表
            List<AgendaFile> agendaFileList = new ArrayList<>();
            Map<String, Object> dataMap = new HashMap<>();
            if (files.length != 0) {
                for (int i = 0; i < files.length; i++) {
                    file = files[i];
                    InputStream is = file.getInputStream(); //得到文件流
                    String fileName = file.getOriginalFilename(); //文件名
                    String contentType = file.getContentType();  //类型
                    String minioFileName = GenerateDateTimeUniqueID.generateSequenceNo() + "-" + fileName; //minio文件名

                    minIoUtil.putObject(personAgenda, minioFileName, is, contentType); //把文件放置Minio桶(文件夹)

                    AgendaFile agendaFile = new AgendaFile();
                    agendaFile.setUuid(UUIDUtils.getUUID());
                    agendaFile.setPersonalAgendaId(agendaUuid);
                    agendaFile.setFileName(fileName);
                    agendaFile.setMinioFileName(minioFileName);
                    agendaFile.setFileSize(fileSize);
                    agendaFileList.add(agendaFile);
                    personalAgendaService.addAgendaAttachFileInfo(agendaFile);
                }
                dataMap.put("agendaFileList", agendaFileList);
                messageBean.setData(dataMap);
                messageBean.setType(MessageConstant.SUCCESS_TYPE);
                messageBean.setCode(MessageConstant.SUCCESS);
                messageBean.setMessage("文件上传成功");
            } else {
                messageBean.setType(MessageConstant.FAIL_TYPE);
                messageBean.setCode(MessageConstant.FAIL);
                messageBean.setMessage("文件上传失败 文件为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("文件上传失败");
        }
        return messageBean;
    }

    /**
     * 通过文件ID下载个人日程附件
     *
     * @return
     */
    @GetMapping(value = "/agenda/downLoadAgendaAttachFileByFileUuid")
    public void downLoadAgendaAttachFileByFileUuid(HttpServletResponse response, @RequestParam Map<String, Object> map) {
        try {
            String uuid = (String) map.get("uuid");
            Map<String, Object> dataMap = new HashMap<String, Object>();
            //查询个人日程信息
            AgendaFile agendaFile = personalAgendaService.selectAgendaAttachFileByFileUuid(uuid);
            ObjectStat objectStat = minIoUtil.getObjectStat(personAgenda, agendaFile.getMinioFileName());
            response.setContentType(objectStat.contentType());
            response.setCharacterEncoding("UTF-8");
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(agendaFile.getFileName(), "UTF-8"));
            //文件流
            InputStream object = minIoUtil.getObject(personAgenda, agendaFile.getMinioFileName());
            IOUtils.copy(object, response.getOutputStream());
            object.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过文件ID删除个人日程附件文件
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/agenda/deleteAgendaAttachFileByFileUuid")
    public MessageBean deleteAgendaAttachFileByFileUuid(@RequestBody Map<String, Object> map) {

        MessageBean messageBean = new MessageBean();
        try {
            String uuid = (String) map.get("uuid");
            Map<String, Object> dataMap = new HashMap<String, Object>();
            //删除个人日程附件信息
            AgendaFile agendaFile = personalAgendaService.selectAgendaAttachFileByFileUuid(uuid);

            personalAgendaService.deleteAgendaAttachFileByFileUuid(uuid);
            //删除minio服务器文件
            minIoUtil.removeObject(personAgenda, agendaFile.getMinioFileName());
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("通过文件ID删除个人日程附件文件成功");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("通过文件ID删除个人日程附件文件失败");
        }
        return messageBean;
    }

}
